package com.zl.pro.controller;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zl.pro.pojo.Order;
import com.zl.pro.pojo.OrderDetails;
import com.zl.pro.pojo.OrderPaging;
import com.zl.pro.pojo.PersonalAssets;
import com.zl.pro.pojo.Transactionflow;
import com.zl.pro.service.OrderService;
import com.zl.pro.service.PersonalAssetsService;
import com.zl.pro.service.TransactionflowService;
import com.zl.pro.service.TrendFeignClient;
import com.zl.pro.service.UserFeignClient;
import com.zl.pro.utils.CreateOrderId;
import com.zl.pro.utils.InvokeInterface;
import com.zl.pro.utils.Result;



@RestController
@RequestMapping("/order")
public class OrderController {

	@Autowired
	OrderService orderService;
	
	@Autowired
	TransactionflowService transactionflowService;
	
	@Autowired
	UserFeignClient userFeignClient;
	
	@Autowired
	PersonalAssetsService personalAssetsService;
	
	@Autowired
	TrendFeignClient trendFeignClient;
	//用户申购
	/*
	 * 申购/定投/赎回添加订单填信息统一调用
	 * 传递参数除表单添加隐藏orderDetailsStatus的值（申购/定投/赎回）
	 * 
	 * */
	@RequestMapping(value="addOrder",method=RequestMethod.POST)
	public Result addOrder(@RequestParam("userid") Long userId,long fundDetailsId,OrderDetails orderDetails) throws ParseException  {
//        System.out.println(userId+"_"+fundDetailsId+"_"+orderDetails);
		Long id1=orderService.findMaxId();
		if(id1==null){id1=(long) 0;}
		long id=id1+1;
		String orderId=new CreateOrderId().getOrderNo(id);
		Order order=new Order();
		order.setOrderid(orderId);
		order.setUserid(userId);
		order.setOrderstatus("未付款");
	/*	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		Date date=df.parse(df.format(new Date()));*/
		order.setOrderdate(new Date());
//		order.setOrderdate(new Date());
		
		order.setFunddetailsid(fundDetailsId);
		order.setAdminoperating("未审核");
		System.out.println(order);
		orderService.addOrder(order);
		
//		OrderDetails orderDetails=new OrderDetails();
		orderDetails.setOrderid(orderId);
//		orderDetails.setOrderamount(orderamount);
//		orderDetails.setHandingfee(handingfee);
//		orderDetails.setOrderdatailsstatus("申购");
		orderService.addOrderDetails(orderDetails);
		Result result=new Result();
		result.setData(200);
		result.setMsg("新增订单成功");
		result.setData(order);
		return result;
	}
	
	@RequestMapping(value="findTime",method=RequestMethod.GET)
	public Result findTime(){

		List<Order> list=orderService.findTime();
		System.out.println(list);
		Result result=new Result();
		result.setStatus(200);
		result.setMsg("查询成功");
		result.setData(list);
		
		return result;
	}
	
	//分页查看订单流水
	@RequestMapping(value="findTransactionflow", method=RequestMethod.POST)
	public Result findTransactionflow(@RequestParam(defaultValue = "1",value = "pageNum")Integer pageNum,Transactionflow transactionflow){
		   //默认第一页开始、一行显示4个
        PageHelper.startPage(pageNum,4);
        //原有的查询方法（需写在startpage后）
        List<Transactionflow> list=transactionflowService.findTransactionflow(transactionflow);

        //pagehelper默认写法、传递session
        PageInfo<Transactionflow> pageInfo = new PageInfo<Transactionflow>(list);
		
		Result result=new Result();
		result.setStatus(200);
		result.setMsg("查询交易流水成功");
		result.setData(pageInfo);
		return result;
	}
	
	/*
	 * 用户确认订单，更新订单状态
	 * 传入输入的密码
	 * */
	@RequestMapping(value="userConfirm",method=RequestMethod.GET)
	public Result userUpdateOrderStatus(@RequestParam("userid") Long userid,@RequestParam("userpwd")String userpwd) {
		//确认用户密码
		Result result=userFeignClient.verifyUserpwd(userid, userpwd);
		if(result.getStatus()==200){
			StringBuilder url = new StringBuilder(
	                "http://127.0.0.1:9901/getTestApi");
	        Map<String, String> params = new HashMap<String, String>();
	        params.put("status", "1");
/*	        params.put("bxm_id", "前端传过来的bxm_de的值");
	        params.put("status","1");//固定值
	        params.put("modeltype", "7");//固定值
*/	        String result1 = InvokeInterface.GetPostUrl(url.toString(), params, "GET",null, 0, 0);
	        System.out.println(result1);
		}
	        
		return result;
	}
	
	/*
	 * 管理员确认审核订单
	 * @param orderid,adminoperating
	 * */
	@RequestMapping(value="adminConfirm",method=RequestMethod.GET)
	public Result adminConfirm(@RequestParam("orderid") String orderid,@RequestParam("adminoperating") String adminoperating){
		orderService.updateOrderAdmin(orderid, adminoperating);
		Result result=new Result();
		result.setStatus(200);
		result.setMsg("审核成功");
		
		return result;
		
	}
	
	/*
	 * 定时发布申购完成的订单
	 * 
	 * */
	
	@RequestMapping(value="test",method=RequestMethod.GET)
//	@Scheduled(cron = "* * 9 */1 * ?")
//	@Scheduled(cron = "* */2 * * * ?")
	public void buyRelease() throws ParseException {
		//获取日期数据
		String string="15:00:00";
		Calendar calendar = Calendar.getInstance();
	    calendar.setTime(new Date());
	    //排除周六周日
	    if(calendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SATURDAY

	      &&calendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
	    	Date date1=null;
	    	Date date2=null;
	    	//周一发布上周周四15点到上周周五15点
	    	if(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.MONDAY){
	    		calendar.add(Calendar.DATE, -3);
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd ");//设置日期格式
				String string2=df.format(calendar.getTime());
				String finalString1=string2+""+string;
				SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			    date1=df1.parse(finalString1);   //昨天三点日期数据
			
				//获取前天三点日期数据
				calendar.add(Calendar.DATE, -4);
				String string3=df.format(calendar.getTime());
				String finalString2=string3+""+string;
		//		System.out.println(finalString2);
			    date2=df1.parse(finalString2);  //前天3点日期数据
		//		System.out.println(date2);
	    	}
	    	//周二发布上周周五15点到本周周一期间
	    	if(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.TUESDAY){
	    		calendar.add(Calendar.DATE, -1);
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd ");//设置日期格式
				String string2=df.format(calendar.getTime());
				String finalString1=string2+""+string;
				SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				date1=df1.parse(finalString1);   //昨天三点日期数据
			
				//获取前天三点日期数据
				calendar.add(Calendar.DATE, -4);
				String string3=df.format(calendar.getTime());
				String finalString2=string3+""+string;
		//		System.out.println(finalString2);
				date2=df1.parse(finalString2);  //前天3点日期数据
		//		System.out.println(date2);
	    	}
	    	
	    
	    	if(calendar.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY 
	    			&& calendar.get(Calendar.DAY_OF_WEEK)!=Calendar.TUESDAY){
				calendar.add(Calendar.DATE, -1);
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd ");//设置日期格式
				String string2=df.format(calendar.getTime());
				String finalString1=string2+""+string;
				SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				date1=df1.parse(finalString1);   //昨天三点日期数据
			
				//获取前天三点日期数据
				calendar.add(Calendar.DATE, -2);
				String string3=df.format(calendar.getTime());
				String finalString2=string3+""+string;
		//		System.out.println(finalString2);
				date2=df1.parse(finalString2);  //前天3点日期数据
		//		System.out.println(date2);
	    	}
//	    	System.out.println(date1+"_"+date2);
			//获取前天15点到昨天15点的订单号
			List<Order> list=orderService.findOrderId(date1, date2);
//			System.out.println(list);
	//		循环发布订单
			for(int i=0;i<list.size();i++){
				OrderDetails orderDetails=orderService.findOrderDetails(list.get(i).getOrderid());
//				System.out.println(orderDetails.getOrderdatailsstatus());
				BigDecimal fundunitprice=null;
				BigDecimal orderamount=null;
				BigDecimal fundnum=null;
				//修改申购时订单详情表的数据
				if(null!=orderDetails.getOrderdatailsstatus()&&orderDetails.getOrderdatailsstatus().equals("申购")){
					//Result result=trendFeignClient.getFundUnitPrice(list.get(i).getFunddetailsid(), string2);
					//BigDecimal fundunitprice=(BigDecimal) result.getData();//调取获取基金单位净值
					 fundunitprice=new BigDecimal(3.99);
					 orderamount=orderDetails.getOrderamount();
					 fundnum= (orderamount.subtract(orderDetails.getHandingfee())).divide(fundunitprice, 4, BigDecimal.ROUND_HALF_UP);
					//更新订单详情表的基金单位净值和基金份额
				    orderService.updateOrderDetails(list.get(i).getOrderid(), fundunitprice, fundnum);
				}
				//修改全部赎回时订单详情表的数据
				if(null!=orderDetails.getOrderdatailsstatus()&&orderDetails.getOrderdatailsstatus().equals("全部赎回")){
					//Result result=trendFeignClient.getFundUnitPrice(list.get(i).getFunddetailsid(), string2);
					//BigDecimal fundunitprice=(BigDecimal) result.getData();//调取获取基金单位净值
					 fundunitprice=new BigDecimal(4.99);
					 fundnum= orderDetails.getFundnum();
					 orderamount=fundunitprice.multiply(fundnum);
					 String percent="1.60%";
					 percent=percent.replace("%","");
					 Float f = Float.valueOf(percent) / 100;
					 BigDecimal decimal = new BigDecimal(f);
					 BigDecimal handingfee=orderamount.multiply(decimal);
					 System.out.println(handingfee);
					//更新订单详情表的基金单位净值和手续费以及订单总金额
				    orderService.updateOrderDetails2(list.get(i).getOrderid(),fundunitprice,orderamount,handingfee);
				}
				
				if(null!=fundunitprice && null!=orderamount&& null!=fundnum){   
				    //发布到个人资产表
				    PersonalAssets personalAssets=new PersonalAssets();
				    personalAssets.setUserid(list.get(i).getUserid());
				    personalAssets.setFunddetailsid(list.get(i).getFunddetailsid());
				    personalAssets.setHoldnum(fundnum);
				    personalAssets.setPersonalassetsstatus("正常");
		            personalAssets.setOrderunitvalue(fundunitprice);
//		            System.out.println(personalAssets);
		            personalAssetsService.addPersonalAssets(personalAssets);
		            
				    //添加到个人流水表
				    Transactionflow transactionflow=new Transactionflow();
				    transactionflow.setOrderid(list.get(i).getOrderid());
				    transactionflow.setFunddetailsid(list.get(i).getFunddetailsid());
				    transactionflow.setUserid(list.get(i).getUserid());
				    transactionflow.setTransactionamount(orderamount);
//				    System.out.println(transactionflow);
				    transactionflowService.addTransactionflow(transactionflow);
				
				}
				
			}
		
	    }
				
	}
	
	
/*	
	申购修改
	@RequestMapping(value="buyRelease")
	public Result buyRelease(Order order)*/
	/**
	 * 查询用户订单记录
	 * @return 返回一个result
	 */
	@RequestMapping(value="orderList",method=RequestMethod.GET)
	public Result OrderList(OrderPaging page) {
		/* SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    
		 Date date = new Date(new java.util.Date().getTime());
		 page.setMinDate(date);*/
		page.setUserId((long) 1);
		Result re = new Result();
		//获取当前条件共有多少条
		Integer count = orderService.orderListByidCount(page);
		page.setRows(count);
		//根据条件 查询集合(在service 实现类中,已经判断页码为空状态)
		List<Order> orli = orderService.orderListByid(page);
		if(orli!=null) {
			
			re.setData(orli);
			re.setMsg("一切正常");
			re.setStatus(201);
		}else {
			
			re.setMsg("查询失败");
			re.setStatus(401);
		}
		return re;
	}
	
	//查询所有订单信息.可传入参数: 用户id 订单id 订单最大时间 订单最小时间  订单状态 管理员审核状态
	@RequestMapping(value="seAllOrder",method=RequestMethod.GET)
	public Result seAllOrder(OrderPaging page) {
		//page.setAdminOperating("未审核"); //测试数据
		Result re = new Result();
		Integer count = orderService.seAllOrderCount(page);
		
		page.setRows(count);
		List<Order> orli = orderService.seAllOrder(page);
		if(orli!=null) {
			re.setData(orli);
			re.setMsg("一切正常");
			re.setStatus(201);
		}else {
			
			re.setMsg("查询失败");
			re.setStatus(401);
		}
		
		return re;
	}
	
	
}

